package io.renren.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.utils.DateUtils;
import io.renren.utils.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.service.InterviewService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation= Propagation.REQUIRED)
@Service("interviewService")
public class InterviewServiceImpl implements InterviewService {
	@Autowired
	private InterviewDao interviewDao;

	@Autowired
	private PersonDispatchDao personDispatchDao;

	@Autowired
	private JobConfirmDao jobConfirmDao;

	@Autowired
	private CustomSettlementDao customSettlementDao;
	@Autowired
	private RecruitdamandDao recruitdamandDao;
	
	@Override
	public InterviewEntity queryObject(Integer id){
		return interviewDao.queryObject(id);
	}
	
	@Override
	public List<InterviewEntity> queryList(Map<String, Object> map){
		return interviewDao.queryList(map);
	}

	@Override
	public List<InterviewEntity> querySettlementList(Map<String, Object> map) {
		return interviewDao.querySettlementList(map);
	}

	@Override
	public int queryTotal(Map<String, Object> map){
		return interviewDao.queryTotal(map);
	}

	@Override
	public int querySettlementTotal(Map<String, Object> map) {
		return interviewDao.querySettlementTotal(map);
	}

	@Override
	public void save(InterviewEntity interview){
		interviewDao.save(interview);
	}
	
	@Override
	public void update(InterviewEntity interview){
		interviewDao.update(interview);
	}
	
	@Override
	public void delete(Integer id){
		interviewDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		interviewDao.deleteBatch(ids);
	}

	@Override
	public List<InterviewEntity> getInterviewByStatus(Map<String, Object> map) {
		List<InterviewEntity> list = interviewDao.getInterviewInfoByStatus(map);
		return list;
	}

	@Override
	@Transactional
	public void updateFirstInterviewStatus(JSONObject jsonObject) throws ParseException {
		int failedstatus = 0; //标记是否面试或者体检不通过.0表示通过，1表示不通过
		int PSstatus = 1; //标记是否体检通过或者延期。0表示通过，1表示不通过
		String idss = jsonObject.getString("ids");
		System.out.println(idss.substring(1,idss.length()-1));
		String[] ids = idss.substring(1,idss.length()-1).split(",");
		String operation = jsonObject.getString("operation");
		String type = jsonObject.getString("type");

//		System.out.println(ids+";"+operation+";"+type);
		Map<String, Object> map = new HashMap<>();
		if("first".equals(type)){//0,初始化,1,通过,2,不通过,3,跳过复试,4,跳过体检，5跳到下个环节
			if("passFir".equals(operation)){
				map.put("first_interview_status","1");
				//failedstatus = 1;
			}else if("failedFir".equals(operation)){
				map.put("first_interview_status","2");
				failedstatus = 1;
			}else if("process".equals(operation)){//面试页面的通过按钮
				map.put("first_interview_status","3");		//到下个流程给个通过状态
				map.put("second_interview_status","0");
			}else if("jumpSec".equals(operation)){
//				map.put("first_interview_status","3");
//				map.put("second_interview_status","1");  //跳过2面,让它为空
			}else if("jumpPS".equals(operation)){
				/*map.put("first_interview_status","4");
				map.put("second_interview_status","3");//second_interview_status:3 表示直接跳过复试，跳过体检
				map.put("physical_examination_status","1");
				PSstatus = 0;*/
				jumpSec(ids,type);
			}
		}else if("second".equals(type)){//0,初始化,1,通过,2,不通过,4,跳过体检,5跳到下个环节
			if("passSec".equals(operation)){
				map.put("second_interview_status","1");
//				map.put("physical_examination_status","0");
			}if("processSec".equals(operation)){
				map.put("second_interview_status","5");
				map.put("physical_examination_status","0");
			}else if("failedSec".equals(operation)){
				map.put("second_interview_status","2");
				failedstatus = 1;
			}else if("jumpPS".equals(operation)){
				/*map.put("second_interview_status","4");
				map.put("physical_examination_status","1");
				PSstatus = 0;*/
				jumpSec(ids,type);


			}
		}else if("ps".equals(type)){//0,初始化,1,通过,2,不通过,3,延时体检
			if("passPS".equals(operation)){
				map.put("physical_examination_status","1");
//				String psStatus = jsonObject.getString("physicalExaminationStatus");

			}else if("failedPS".equals(operation)){
				map.put("physical_examination_status","2");
				failedstatus = 1;
			}else if("laterPS".equals(operation)){	 //延时体检后直接添加到派遣表，边体检边添加
				map.put("physical_examination_status","3");
				map.put("later_pe_time",jsonObject.getString("psTime"));
				PSstatus = 0;
			}
		}

		Calendar ca = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		String date = format.format(ca.getTime());

		int res = 0;
		for (String id : ids) {
			id = id.substring(1,id.length()-1);
			System.out.println("id:"+id);
			map.put("id",id);
			InterviewEntity interviewEntity =	interviewDao.queryObject(id);

			//wdj add start
			if (interviewEntity !=null ) {
				if("first".equals(type) && "jumpSec".equals(operation)){ //面试流程的体检操作
					//判断所属的结算点配置要不要体检
					CustomSettlementEntity customSettlementEntity = customSettlementDao.queryObject(interviewEntity.getCompanyid());
					String healthCheckup = customSettlementEntity.getHealthCheckup();//公司是否需要体检
					if("0".equals(healthCheckup)) { //需要体检
						PSstatus = 1; //不派遣
						map.put("first_interview_status","3");   //通过，表示合格的前提下，到下一轮
						map.put("physical_examination_status","0"); //添加到体检流程
					} else {
						map.put("first_interview_status","3");   //通过，表示合格的前提下，到下一轮
						PSstatus = 0; //免体检直接派遣
					}

				}
				if("ps".equals(type) && "passPS".equals(operation)){  //表示体检流程的合格操作
					if("3".equals(interviewEntity.getPhysicalExaminationStatus())) { //正常体检通过后添加到派遣表，延时体检通过的不添加
						PSstatus = 1; //不派遣
					} else if ("0".equals(interviewEntity.getPhysicalExaminationStatus())) {
						PSstatus = 0; //直接派遣
					}
				}

			}
			//wdj add end

			if(interviewEntity!=null&&interviewEntity.getRecruitdamandid()!=null){
				RecruitdamandEntity recruitdamandEntity = new RecruitdamandEntity();
				recruitdamandEntity.setId(Integer.valueOf(interviewEntity.getRecruitdamandid()));
				if("first".equals(type)){
					if("passFir".equals(operation)){
						recruitdamandEntity.setFircount(1);
					}else if("process".equals(operation)){//面试页面的通过按钮
						recruitdamandEntity.setJoinseccount(1);
					}
				}else if("second".equals(type)){
					if("passSec".equals(operation)){
						recruitdamandEntity.setSeccount(1);
					}if("processSec".equals(operation)){
						recruitdamandEntity.setJoinphysicalcount(1);
					}
				}else if("ps".equals(type)&&"passPS".equals(operation)){
					recruitdamandEntity.setPhysicalcount(1);
					if("3".equals(interviewEntity.getPhysicalExaminationStatus())) { //正常体检通过后添加到派遣表，延时体检通过的不添加
						PSstatus = 1;
					} else if ("0".equals(interviewEntity.getPhysicalExaminationStatus())) {
						PSstatus = 0;
					}

				}
				recruitdamandDao.updatePeople(recruitdamandEntity);
			}

			if(!"jumpPS".equals(operation)) {//免体检上面有做处理
				res = interviewDao.updateFirstInterviewStatus(map);
			}
			//如果面试或者体检不通过，要改变员工的状态为可以再次参加筛选工作
			if(failedstatus == 1){
				res = interviewDao.changeEmpFreeFlag(interviewEntity.getEmpid());
			}

			//如果体检合格，那么就要把合格的员工添加到人员派遣表中去
			if(PSstatus==0){
				InterviewEntity interview = interviewDao.queryObject(id);
				PersonDispatchEntity person = new PersonDispatchEntity();
				person.setInterviewId(interview.getId().toString());
				person.setSettlementId(interview.getCompanyid());
				person.setPersonId(interview.getEmpid()+"");
				person.setStation(interview.getJobname());
				person.setFileState("0");
				person.setInjury("0");
				person.setPension("0");
				person.setUnemployment("0");
				person.setMedicare("0");
				person.setMaternity("0");
				person.setAccumulationFund("0");
				person.setFiveOneInsurance("0");
				person.setOperator("admin");
				//person.setOperationDate(ca.getTime());
				person.setEnable(0);
				person.setDispatchStatus("dispatchstatus01");
				person.setPhysicalExaminationStatus("pestatus01");
				personDispatchDao.saveByDynamicCol(person);
			}
			if("first".equals(type)) {
				//0,初始化,1,通过,2,不通过,3,跳过复试,4,跳过体检
				if ("passFir".equals(operation)) {
					InterviewEntity interview = interviewDao.queryObject(id);
					JobConfirmEntity jobConfirmEntity = new JobConfirmEntity();
					jobConfirmEntity.setAge(interview.getAge());
					jobConfirmEntity.setCertificate(interview.getCertificate());
					jobConfirmEntity.setCompany(interview.getCompany());
					jobConfirmEntity.setCompanyid(interview.getCompanyid());
					jobConfirmEntity.setDamandid(interview.getDamandid());
					jobConfirmEntity.setEducation(interview.getEducation());
					jobConfirmEntity.setEmpid(interview.getEmpid());
					jobConfirmEntity.setEmpname(interview.getEmpname());
					jobConfirmEntity.setJobid(interview.getJobid());
					jobConfirmEntity.setJobname(interview.getJobname());
					jobConfirmEntity.setMarried(interview.getMarried());
					jobConfirmEntity.setSex(interview.getSex());
					jobConfirmEntity.setStatus("0");
					//jobComfirmEntity.setBatch(date);
					jobConfirmDao.saveByDynamicCol(jobConfirmEntity);
				}
			}


		}

	}

	@Override
	public int queryTotalInterview(Map<String, Object> map) {
		return interviewDao.queryTotalInterview(map);
	}


	public void jumpSec(String[] ids,String type){
		Map<String, Object> map = new HashMap<>();
		for (String id : ids) {
			id = id.substring(1,id.length()-1);
			System.out.println("id:"+id);
			InterviewEntity interview = interviewDao.queryObject(id);
			CustomSettlementEntity customSettlementEntity = customSettlementDao.queryObject(interview.getCompanyid());
			String healthCheckup=customSettlementEntity.getHealthCheckup();//公司是否需要体检
			if("0".equals(healthCheckup)){//需要体检
				if("first".equals(type)) {
					map.put("first_interview_status","3");
				}
				map.put("second_interview_status","1");

			}else{
				if("first".equals(type)) {
					map.put("first_interview_status", "4");
					map.put("second_interview_status", "3");//second_interview_status:3 表示直接跳过复试，跳过体检
					map.put("physical_examination_status", "1");
				}else{
					map.put("second_interview_status","4");
					map.put("physical_examination_status","1");

				}
				//PSstatus = 0;
				PersonDispatchEntity person = new PersonDispatchEntity();
				person.setInterviewId(interview.getId().toString());
				person.setSettlementId(interview.getCompanyid().toString());
				person.setPersonId(interview.getEmpid().toString());
				person.setStation(interview.getJobid().toString());
				person.setFileState("0");
				person.setInjury("0");
				person.setPension("0");
				person.setUnemployment("0");
				person.setMedicare("0");
				person.setMaternity("0");
				person.setAccumulationFund("0");
				person.setFiveOneInsurance("0");
				person.setOperator("admin");
				//person.setOperationDate(ca.getTime());
				person.setEnable(0);
				person.setDispatchStatus("dispatchstatus01");
				person.setPhysicalExaminationStatus("pestatus01");
				personDispatchDao.saveByDynamicCol(person);
			}
			map.put("id",id);
			interviewDao.updateFirstInterviewStatus(map);

		}
	}

//系统确认
	@Override
	public void sysConfirm() {
		try {
			Map<String, Object> map = new HashMap<String, Object>();

			List<InterviewEntity> InterviewEntityList = querySettlementList(map);
			for (InterviewEntity interviewEntity : InterviewEntityList) {
				if (interviewEntity.getInjuryInsuredDate() != null&&"0".equals(interviewEntity.getAuditResult())
						&&"".equals(interviewEntity.getBatchCode())) {
					int months = DateUtils.joinMonths(interviewEntity.getInjuryInsuredDate(), new Date());
					if(months>=1){
						interviewEntity.setConfirmStatus("1");
					}else{
						interviewEntity.setConfirmStatus("0");
					}
					interviewDao.update(interviewEntity);
				}
			}
		}catch (RRException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void confirm(JSONObject jsonObject) {
		String ids = jsonObject.get("ids").toString();
		String[] id = ids.split(",");
		String status = jsonObject.get("status").toString();
		for(int i=0;i<id.length;i++){
			interviewDao.confirm(id[i],status);
		}
	}

	@Override
	public void addBatchCode(JSONObject jsonObject) {
		String ids = jsonObject.get("ids").toString();
		String[] id = ids.split(",");
		String batchcode = jsonObject.get("yearmonth").toString();
		for(int i=0;i<id.length;i++){
			interviewDao.addBatchCode(id[i],batchcode);
		}
	}
	@Override
	public void audit(JSONObject jsonObject,SysUserEntity sysUserEntity){
		String ids = jsonObject.get("ids").toString();
		String[] id = ids.split(",");
		for(int i=0;i<id.length;i++){
			InterviewEntity interviewEntity = new InterviewEntity();
			interviewEntity.setId(Integer.valueOf(id[i]));
			interviewEntity.setAuditDate(new Date());
			interviewEntity.setAuditUser(sysUserEntity.getUsername());
			interviewEntity.setAuditResult("1");
			interviewDao.audit(interviewEntity);
		}

	}
}
